//
//  HSDSpidermanNetworkInfoHelper.m
//  GoldenCard
//
//  Created by 正合适 on 2018/3/22.
//  Copyright © 2018年 合时代. All rights reserved.
//

#import "HSDSpidermanNetworkInfoHelper.h"
#import "HSDSpidermanNetworkManager.h"
#import "HSDSpiderMacro.h"
#import <AFNetworking/AFNetworking.h>
#import "HSDSpidermanTools.h"
static NSString *str(NSInteger val) {
    return [NSString stringWithFormat:@"%ld",val];
}

// 网络状态改变通知
NSString *const kNetstatusChangeNotify = @"com.hsd.spiderman.netstatuschangednotify";

@implementation HSDSpidermanNetworkInfoHelper
- (instancetype)init {
    self = [super init];
    if (self) {
        _netModel = [[HSDSpidermanNetworkInfoModel alloc] init];
        _netModel.carrier = [HSDSpidermanTools phoneOperater];
        _netModel.wifi = @"0";
//        [self addObserver];
    }
    return self;
}

//- (void)addObserver {
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeAction) name:UIApplicationDidBecomeActiveNotification object:nil];
//}

- (void)startRead {
    __weak typeof(self) weakself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [weakself getNetInfo];
    });
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [weakself netStatus];
    });
}

- (void)getNetInfo {
    NSURL *ipURL = [NSURL URLWithString:kNetInfoApi];
    NSData *data = [NSData dataWithContentsOfURL:ipURL];
    if (!data) return;
    NSDictionary *ipDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    if ([ipDic.allKeys containsObject:@"code"] && [ipDic[@"code"] intValue]== 0) {
        __weak typeof(self) weakself = self;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSLock *lock = [NSLock new];
            [lock lock];
            weakself.netModel.ipAddress = ipDic[@"data"][@"ip"];
            [lock unlock];
        });
    }
}

- (void)netStatus {
    __weak typeof(self) weakself = self;
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSLock *lock = [NSLock new];
            [lock lock];
            if (status == 2) {
                weakself.netModel.wifi = @"1";
//                [[NSNotificationCenter defaultCenter] postNotificationName:kNetstatusChangeNotify object:nil];
            } else {
                weakself.netModel.wifi = @"0";
            }
            [lock unlock];
        });
    }];
}

@end
